package com.oeandn.message.context;




import com.oeandn.message.event.EventListener;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@Service
public class EventManager {


	
	private Map<String, List<EventListener>> eventMap = new ConcurrentHashMap<String, List<EventListener>>();
	
	/**
	 * 注册事件和事件监听器
	 * @param eventType
	 * @param listener
	 */
	public synchronized void regEventListener(String eventType, EventListener listener){
		if(StringUtils.isEmpty(eventType)){
			throw new RuntimeException("eventType为空");
		}
		if(listener == null){
			throw new RuntimeException("listener为空");
		}
		log.info("注册：eventType:"+eventType+", listener:" + listener);
		List<EventListener> listenerList = eventMap.get(eventType);
		if(listenerList == null){
			listenerList = new ArrayList<EventListener>();
			listenerList.add(listener);
			eventMap.put(eventType, listenerList);
		}else{
			if(!listenerList.contains(listener)){
				listenerList.add(listener);
			}else{
				log.warn("已注册listener, eventType:"+eventType+", listener:" + listener);
			}
		}
	}
	
	
	public List<EventListener> getListeners(String eventType){
		if(StringUtils.isEmpty(eventType)){
			log.warn("eventType为空， 返回");
			return null;
		}
		List<EventListener> listenerList = eventMap.get(eventType);
		return listenerList;
		
	}
}
